﻿using System;
using System.Collections.Generic;
using System.Text;

using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Runtime.InteropServices;

using SuperMapLib;

namespace JR_RouteAlarm
{
    class Utility : IDisposable
    {
        #region 定数
        //フィールド
        public const string USER_FIELD = "SmUserID";
        public const string FEATURE = "feature_cd";
        public const string DAIBUN = "daibun_cd";
        public const string TSUUSHO = "tsuusho_cd";
        public const string AREA_CD = "area_cd";            // エリア番号
        public const string KIROTEI_BGN = "kirotei_bgn";    // 始端キロ程
        public const string KIROTEI_END = "kirotei_end";    // 終端キロ程
        public const string ALARM_ROUTE = "alarm_route";    // 鳴動対象の発報線区
        public const string ALARM_AREA = "alarm_area";      // 鳴動対象の発報エリア
        public const string EXTRA_INFO = "extra_info";      // 始終端付帯情報
        public const string KIROTEI = "kirotei";            // キロ程

        public const string LAST_STOP = "終点";
        public const string BUFFER_TITLE_200 = "Buffer200_";
        public const string THEME_COLOR_CAPTION = "色分け主題図";
        public const string THEME_LABLE_CAPTION = "見出し主題図";
        public const string WORKING_DIR_DEFAULT = @"\working";  // 作業中のフォルダ
        public const string LOG_FILE_NAME = "社名・ロゴマーク組合せ（BMP）.bmp";
        public const string PROPERTY_TABLE_NAME = "エリア境界"; // エリア情報の属性テーブル
        public const string KIROTEI_PREFIX = "キロ標_";
        public const string INFO_NO_ALARMING = "他線区からの鳴動受信なし";
        public const string MSG_MANUALLY_STOP = "アプリケーションがユーザーより中止された！";
        public const double MAX_DISTANCE_TOLERANCE = 10D;   // キロ程のポイントは線路ラインの上であるかどうかを判断するデフォルト許容
        public const int BUFFER_ALARM_DISTANCE_2 = 200;     // 作成するバッファーの(幅)サイズ
        public const int FLAG_LAST_STOP = 9;

        //フィールド長さ
        public const int SIZE_AREACD = 6;
        public const int SIZE_KIROTEI_BGN = 6;
        public const int SIZE_KIROTEI_END = 24;
        public const int SIZE_EXTRA_INFO = 32;
        public const int SIZE_ALARM_ROUTE = 20;
        public const int SIZE_ALARM_AREA = 22;

        //レイヤー上に表示している文字サイズ
        public const int LABEL_FONT_HIGHT = 200;
        public const int LABEL_FONT_WIDTH = 80;

        //各種限界値
        public const int MAX_KIROTEI_DATASETS = 10;
        public const int MAX_CROSSING_POINTS = 40;
        public const int MAX_ROUTES = 60;
        public const int MAX_DIVIDED_LINES = 50;
        public const int MAX_MULTIPLE_LINES = 300;
        public const int MAX_ALARM_TARGETS = 7;
        public const int MAX_LINE_CHARS = 31;

        //レイアウトとマップ連携
        public const int MAP_ON_LAYOUT_MARGIN_TOP = 0;
        public const int MAP_ON_LAYOUT_MARGIN_LEFT = 0;

        #endregion

        /*変数*/
        public static string s_AppPath = String.Empty;
        public static string s_WkspName = String.Empty;
        public static string s_DatasourceAlias = String.Empty;
        public static string s_NewDatasetName = String.Empty;

        //作業中のワークスペース
        private AxSuperMapLib.AxSuperWorkspace superWksp = null;

        /// <summary>
        /// ワークスペースの一部を初期化
        /// </summary>
        /// <param name="superWksp">ワークスペースオブジェクト</param>
        public Utility(AxSuperMapLib.AxSuperWorkspace superWksp)
        {
            s_AppPath = System.Reflection.Assembly.GetExecutingAssembly().Location.Substring(0,
                    System.Reflection.Assembly.GetExecutingAssembly().Location.LastIndexOf('\\'));
            this.superWksp = superWksp;
        }

        /// <summary>
        /// ワークスペースのいろいろな情報入手
        /// </summary>
        /// <param name="wkspPath">ワークスペースのパス</param>
        /// <param name="copyDir">変換元フォルダ</param>
        public void InitializeWksp(string wkspPath, string copyDir)
        {
            string wkspDir = wkspPath.Substring(0, wkspPath.LastIndexOf('\\'));
            s_WkspName = wkspPath.Substring(wkspPath.LastIndexOf('\\') + 1);
            string workingDir = wkspDir + WORKING_DIR_DEFAULT;
            if (!workingDir.Equals(copyDir))
            {
                workingDir = copyDir;
            }
            string workingPath = workingDir + '\\' + s_WkspName;

            try
            {
                string[] strFiles = 
                    Directory.GetFiles(wkspDir, "*.*", SearchOption.TopDirectoryOnly);
                Directory.CreateDirectory(workingDir);
                for (int i = 0; i < strFiles.Length; i++)
                {
                    File.Copy(strFiles[i], 
                        workingDir + strFiles[i].Substring(strFiles[i].LastIndexOf('\\')), true);
                }
            }
            catch (System.Threading.ThreadAbortException ae)
            {
                throw ae;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            if (!superWksp.Open(workingPath))
            {
                throw new Exception("Workspace open failed!");
            }
        }

        /// <summary>
        /// マルチストレースより、取消する
        /// </summary>
        public void CancelOperation()
        {
            Dispose();
        }

        /// <summary>
        /// 全部リソースを解放
        /// </summary>
        public void Dispose()
        {
            RouteDataset.ReleaseMemory(true);

            if (superWksp.Modified)
            {
                superWksp.Save();
            }
            superWksp.Close();

            //Marshal.ReleaseComObject(superWksp); //COMではない？
            superWksp = null;

            GC.SuppressFinalize(this);

            MessageBox.Show("Release memory OK!");
        }
    }
}
